package com.bootdo.mq;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import com.bootdo.common.utils.DateUtils;

/**
 * @Desc
 * @auth xia.zhuming
 * @date 2020/4/10
 *
 */
public class SendMessageToMQ implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(SendMessageToMQ.class);

    private DirectExchange directExchange;
    private String queueName;
    private String msg;
    private RabbitAdmin rabbitAdmin;
    private RabbitTemplate rabbitTemplate;

    public SendMessageToMQ(DirectExchange directExchange, String queueName, String msg, RabbitAdmin rabbitAdmin, RabbitTemplate rabbitTemplate) {
        this.directExchange = directExchange;
        this.queueName = queueName;
        this.msg = msg;
        this.rabbitAdmin = rabbitAdmin;
        this.rabbitTemplate = rabbitTemplate;
    }
    public Message getMessage(String messageType, Object msg){
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setContentType(messageType);
        Message message = new Message(msg.toString().getBytes(),messageProperties);
        return message;
    }
	@Override
	public void run() {
		Queue queue = new Queue(queueName);
        //addQueue(queue);
        Binding binding = BindingBuilder.bind(queue).to(directExchange).withQueueName();
        rabbitAdmin.declareBinding(binding);
        Message message = getMessage(MessageProperties.CONTENT_TYPE_JSON,msg);
        //设置消息内容的类型，默认是 application/octet-stream 会是 ASCII 码值
        rabbitTemplate.convertAndSend(directExchange.getName(), queueName, message);
        logger.info("前往通道："+queueName+"的消息已经成功发射，请等待接收"+ DateUtils.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss.SSS"));
	}
}
